package com.th.basemodel.base

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import com.th.basemodel.bean.LoadAction
import com.th.basemodel.ext.toast
import com.th.basemodel.ui.LoadingDialogManager
import java.lang.reflect.ParameterizedType

/**
 * 加入ViewModel与LoadState
 * 默认为Loading布局的懒加载
 */
abstract class BaseVDBLazyLoadingFragment2<VB : ViewDataBinding> : AbsFragment() {

    protected lateinit var mBinding: VB
    private var isViewCreated = false//布局是否被创建
    private var isLoadData = false//数据是否加载
    private var isFirstVisible = true//是否第一次可见

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        isViewCreated = true

        init()
        initDefaultLiveData()
        startObserve()
    }

    open protected fun createViewBinding() {

        val clazz: Class<*> =  (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] as Class<VB>

        try {
            mBinding = clazz.getMethod(
                "inflate", LayoutInflater::class.java
            ).invoke(null, layoutInflater) as VB

        } catch (e: Exception) {
            e.printStackTrace()
            throw IllegalArgumentException("ViewBinding == null")
        }

    }

    override fun setContentView(container: ViewGroup?): View {
        createViewBinding()
        mBinding.lifecycleOwner = viewLifecycleOwner

        return mBinding.root
    }


    abstract fun startObserve()
    abstract fun init()
    abstract fun onLazyInitData()


    private fun initDefaultLiveData() {
        getVm().mLoadActionLiveData.observe(this, Observer {
            when (it.action) {
                LoadAction.STATE_LOADING ->{
                    LoadingDialogManager.get().showLoading(requireActivity())
                }
                LoadAction.STATE_SUCCESS ->{
                    LoadingDialogManager.get().dismissLoading()
                }
                LoadAction.STATE_ERROR ->{
                    LoadingDialogManager.get().dismissLoading()
                    toast(it.message)
                }
            }
        })
    }

    abstract fun getVm(): BaseViewModel

    // ============================  Lazy Load begin ↓  =============================

    override fun onResume() {
        super.onResume()
        if (isFragmentVisible(this)  && isViewCreated && this.isAdded) {
            onLazyInitData()
            isLoadData = true
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isFragmentVisible(this)  && isViewCreated && this.isAdded) {
            onLazyInitData()
            isLoadData = true
        }
    }

    override fun onDestroy() {
        super.onDestroy()

        isViewCreated = false
        isLoadData = false
        isFirstVisible = true
    }

    /**
     * 当前Fragment是否对用户是否可见
     * @param fragment 要判断的fragment
     * @return true表示对用户可见
     */
    private fun isFragmentVisible(fragment: Fragment?): Boolean {
        return !fragment?.isHidden!! && fragment.userVisibleHint
    }
}